import abc
from app.libs.exception import APIException, AuthFailed, Forbidden, NotFound
from app.libs.forms import ResourceByIDForm, SearchForm


class BaseService:
    # @modify 令牌校验的方法，集成到了表达校验器中
    # @classmethod
    # def check_token_and_get_user(cls) -> User:
    #     token = request.headers.get('token', default=None, type=str)
    #     if not token:
    #         raise Forbidden('请传入token再请求')
    #     user = TokenService.verify_jwt_and_get_user(token=token)
    #     return user  # 获取当前请求的用户信息
    __metaclass__ = abc.ABCMeta

    @classmethod
    def optional_404(cls, query_result, error_msg=None, check_list=False):
        """ 如果result为空将会抛出自定义的404异常|列表资源不会抛出异常 """
        return cls.optional(query_result, NotFound(error_msg), check_list)

    @classmethod
    def optional_403(cls, query_result, error_msg=None, check_list=False):
        """ 如果result为空将会抛出自定义的404异常|列表资源不会抛出异常 """
        return cls.optional(query_result, Forbidden(error_msg), check_list)

    @classmethod
    def optional_401(cls, query_result, error_msg=None, check_list=False):
        """ 如果result为空将会抛出自定义的404异常|列表资源不会抛出异常 """
        return cls.optional(query_result, AuthFailed(error_msg), check_list)

    @staticmethod
    def optional(query_result, exception: APIException, check_list=False):
        if query_result is None:
            raise exception
        if check_list and isinstance(query_result, list) and len(query_result) == 0:
            raise exception
        return query_result

    @abc.abstractclassmethod
    def gets(cls):
        pass

    @abc.abstractclassmethod
    def get_by_id(cls):
        pass

    @abc.abstractclassmethod
    def del_by_id(cls):
        pass

    @abc.abstractclassmethod
    def save2db(cls, vs_vo):
        pass

    @abc.abstractclassmethod
    def search(cls, form: SearchForm):
        pass
        